import fs from 'fs';
import os from 'os';
import path from 'path';
import { post } from 'request';
import { unlink, write_file } from './fs';
// ! this service is not used any more

interface Message {
	host: string; spaceid: string; id: string; data: string; file_name: string;
}

export default function atom(msg: Message) {
	return new Promise<{
		_id: string;
		length: number;
		chunkSize: number;
		uploadDate: string;
		md5: string;
		filename: string;
		contentType: string;
		metadata: {
			originialFileName: string;
			productid: string;
		}
	}>(async (resolve, reject) => {
		const data = msg.data;
		const host = msg.host;
		const productid = msg.spaceid;
		const id = msg.id;
		const file_name = msg.file_name;
		const _blob = Buffer.from(data.replace(/data:.*;base64,/, ''), 'base64');
		if (_blob && _blob instanceof Buffer) {
			const uri = `${host}/fsweb/upload?productid=${productid}`;

			const file_path = path.join(os.tmpdir(), file_name);
			await write_file(file_path, _blob);

			const formData = {
				up_load_file: fs.createReadStream(file_path)
			};
			const form = { id };
			post({
				// form,
				formData,
				uri
			}).on('data', async (buf: Buffer) => {
				try {
					await unlink(file_path);
					const res = JSON.parse(buf.toString('utf8'));
					if (res.code === 0) {
						reject(res.code_msg);
					} else if (res[0]) {
						resolve(res[0]);	// Just return Id
					} else {
						reject('Error');
					}
				} catch (e) {
					reject(e.message);
				}
			}).on('error', (err: any) => {
				console.error(err);
				reject(err.message);
			});
		} else if (typeof data === 'string') {
			const uri = `${host}/fsweb/upload`;

			const json = {
				id,
				file_string: data,
				productid
			};
			post({
				json,
				uri
			}).on('data', (buf: Buffer) => {
				try {
					const res = JSON.parse(buf.toString('utf8'));
					if (res.code === 0) {
						reject(res.code_msg);
					} else if (res[0]) {
						resolve(res[0]);	// Just return Id
					} else {
						reject('Error');
					}
				} catch (e) {
					reject(e.message);
				}
			}).on('error', (err: any) => {
				console.error(err);
				reject(err.message);
			});
		} else {
			reject('file type not surported');
		}
	});
}
